import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:baseProjectFlutter/utils/other/log/log.dart';

import '../../config/app_colors.dart';
import '../../config/theme.dart';
import '../../utils/lifecycle/lifecycle.dart';
import '../../widgets_common/load_switch/context_data.dart';
import '../../widgets_common/load_switch/load_switch.dart';

//基础的BasePage 方便管理StatefulWidget
abstract class BasePage extends StatefulWidget {
  const BasePage({super.key});
}

abstract class BaseState<T extends BasePage> extends State<T> with WidgetsBindingObserver, LifecycleOwner {
  String title = "";

  String get pageName => '${runtimeType.toString()},$title';

  @override
  void initState() {
    super.initState();
    LogUtils.i("创建:$pageName界面");
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    LogUtils.i("页面：$title，，$runtimeType 调用了 build");
    return createMainWidget(context);
  }

  Color get backgroundColor => AppColors.color_ececec;

// AppBar + Content
  Widget createMainWidget(BuildContext context) {
    return Theme(
        data: ThemeUtils.getCommonAppBarTheme(context),
        child: Scaffold(
          backgroundColor: backgroundColor,
          appBar: createAppbar(),
          floatingActionButton: floatingActionButton(),
          body: createContentWidget(context),
        ));
  }

  /// 没有AppBar 这里加入布局切换
  Widget createContentWidget(BuildContext context) {
    return LoadStateLayout(
      controller: loadStateController,
      errorRetry: onRetryClick,
      emptyRetry: onEmptyClick,
      child: buildWidget(context),
    );
  }

  LoadStateController get loadStateController => LoadStateController();

  // @protected
  // PreferredSizeWidget? createAppbar() => AppBar(
  //       title: Text(
  //         title,
  //         style: const TextStyle(fontSize: 16, color: AppColors.black_33),
  //       ),
  //       centerTitle: true,
  //       backgroundColor: AppColors.white,
  //     );
  @protected
  PreferredSizeWidget? createAppbar() {
    return null;
  }

  //不同部分UI处理，在子类必须实现buildWidget()函数
  @protected
  Widget buildWidget(BuildContext context);

  //悬浮按钮
  @protected
  Widget? floatingActionButton() {
    return null;
  }

  @protected
  void onEmptyClick(ContextData contextData) {}

  @protected
  void onRetryClick(ContextData contextData) {}

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    LogUtils.i("didChangeDependencies: $pageName界面");
  }

  @override
  void didUpdateWidget(covariant T oldWidget) {
    super.didUpdateWidget(oldWidget);
    LogUtils.i("didUpdateWidget: $pageName界面");
  }

  @override
  void deactivate() {
    super.deactivate();
    LogUtils.i("停用:$pageName界面");
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
    LogUtils.i("销毁$pageName界面");
  }
}
